package com.ecosoft.config.spi.property;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ecosoft.config.IConfig;


public class PropertyConfig implements IConfig {
	private static final Logger LOG = LoggerFactory.getLogger(PropertyConfig.class);
	private Properties propertes;
	private String file;
	public PropertyConfig(String file)
	{
		this.file = file;
		propertes = new Properties();
		try {
			propertes.load(new FileInputStream(new File(file)));
		} catch (FileNotFoundException e) {
			LOG.error("The file ("+file+") is not instanced to FileInputStream.",e);
		} catch (IOException e) {
			LOG.error("An error occurs during loading the  file "+file+".",e);
		}
	}
	
	/**
	 * Brief Intro Here
	 */
	private static final long serialVersionUID = 1L;
	public Map<String, String> getPropertyStartWith(String prefix) {
		HashMap<String, String> result = new HashMap<String, String>();
		if (prefix != null) {
			List<String> names = propertyNamesList();
			for (String key : names) {
				if (key.startsWith(prefix)) {
					result.put(key, getProperty(key));
				}
			}
		}
		return result;
	}
	public List<String> propertyNamesList() {
		Enumeration iter = propertes.propertyNames();
		List<String> names = new ArrayList<String>();
		while (iter.hasMoreElements()) {
			names.add((String) iter.nextElement());
		}
		return names;
	}

	public boolean containsKey(String key) {
		return propertes.containsKey(key);
	}
	
	public void removeProperty(String strName) {
		propertes.remove(strName);
		update();
	}

	private synchronized void update() {
		FileOutputStream out = null;
		try {
		    out = new FileOutputStream(file);
			propertes.store(out, "");
		} catch (FileNotFoundException e) {
			LOG.error("The file (" + file
					+ ") is not instanced to FileOutputStream.", e);
		} catch (IOException e) {
			LOG.error("The file (" + file + ") is not stored to the file "
					+ file, e);
		}finally{
			if(out!=null)
			{
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					LOG.error("", e);
				}
				
			}
		}
	}
	public String updateProperty(String key, String value) {
		String old = (String)propertes.setProperty(key, value);
		this.update();
		return old;
	}
	public String getProperty(String key) {
		return propertes.getProperty(key);
	}
}
